<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.view');

class OwnserviceControllerUser extends JController
{
	/**
	 * Controller construct
	*/
	function __construct(){
		parent::__construct();
	}

	/**
	 * Method to get detail user
	 *
	 * @return void
	 * @since 1.0
	*/
	function detail() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25){
			$canView		= Ownservice::checkAccess('user', 'view', 'user', 'all');
			if ( !$canView ) {
				//JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('user', 'html');

		// Get/Create the model
		$model = & $this->getModel('User');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('default');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get form  edit user
	 *
	 * @return void
	 * @since 1.0
	 */
	function edit(){

		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canEdit	= Ownservice::checkAccess('user', 'edit', 'user', 'all');
			if ( !$canEdit ) {
				//JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('user', 'html');

		// Get/Create the model
		$model = & $this->getModel('User');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();

	}

	/**
	* Method to add an custom account
	*
	* @access	public
	* @since	1.0
	*/
	function add() {

		global $mainframe;

		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		if($user->gid < 25) {
			$canAdd		= Ownservice::checkAccess('user', 'add', 'user', 'all');
			if ( !$canAdd ) {
				//JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		// Create the view
		$view = & $this->getView('user', 'html');

		// Get/Create the model
		$model = & $this->getModel('User');

		// Push the model into the view (as default)
		$view->setModel($model, true);

		// Set the layout
		$view->setLayout('form');

		// Display the view
		$view->display();
	}

	/**
	 * Logic to save user
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function save() {

		// Check for request forgeries
		JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

		global $mainframe;

		//Initialise variables
		$db		= & JFactory::getDBO();
		$acl	= & JFactory::getACL();
		$me		= & JFactory::getUser();
		$ownuser= & Ownservice::getUser();
		$app	= & JFactory::getApplication();

		// Create a new JUser object
		$user = new JUser(JRequest::getVar( 'user_id', 0, 'post', 'int' ));

		$isNew 	= ($user->get('id') < 1);

		// Get vars 
		$post = JRequest::get('post');

		// Get/Create the model
		$model = & $this->getModel('User');

		//set full name
		$post['name']		= JRequest::getVar('firstname', '', 'post', 'string').' '.strtoupper(JRequest::getVar('lastname', '', 'post', 'string'));
		
		//set Username
		if($isNew) {
			$post['username']	= OwnserviceHelper::usernameFormat($post['firstname'], $post['lastname'], $post['birthday']);
		}

		//check username already exists?
		if( ($model->checkUsername(trim($post['username']))) && ($isNew) )
		{
			$chars = array('A'=>'A', 'B'=>'B','C'=>'C','D'=>'D','E'=>'E','F'=>'F','G'=>'G','H'=>'H','I'=>'I','J'=>'J','K'=>'K','L'=>'L','M'=>'M','N'=>'N','O'=>'O','P'=>'P','Q'=>'Q','R'=>'R','S'=>'S','T'=>'T','U'=>'U','V'=>'V','W'=>'W','X'=>'X','Y'=>'Y','Z'=>'Z');

			foreach($chars as $char)
			{
				if(!$model->checkUsername(trim($post['username']).$char))
				{
					$post['username'] = trim($post['username']).$char;
					break;
				}
			}
		}

		if(!$isNew) {
			$post['password']	= JRequest::getVar('password', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$post['password2']	= JRequest::getVar('password2', '', 'post', 'string', JREQUEST_ALLOWRAW);
		} else {
			$post['password']	= '123456';
			$post['password2']	= $post['password'];
		}

		$post['gid']	= isset($post['gid'])?$post['gid']: 18;

		$id = 0;

		if(!$isNew){
			$id			= JRequest::getVar( 'id', 0, 'post', 'int');
			$post['id'] = JRequest::getVar( 'user_id', 0, 'post', 'int');
		}

		//set email
		if($post['email'] == '') {
			$post['email'] = $post['username'].'@gmail.com';
		}

		if (!$user->bind($post)) {
			$mainframe->enqueueMessage(JText::_('OWNSERVICE_ERROR_SAVE_USER'), 'message');
			$mainframe->enqueueMessage($user->getError(), 'error');
			return $this->execute('edit');
		}

		/*
	 	 * Lets save the JUser object
	 	 */
		if (!$user->save()) {
			$mainframe->enqueueMessage(JText::_('OWNSERVICE_ERROR_SAVE_USER'), 'message');
			$mainframe->enqueueMessage($user->getError(), 'error');
			return $this->execute('edit');
		}

		//delete own data of user all
		if($isNew) {
			//own users
			$query = 'DELETE * FROM #__ownservice_users WHERE user_id='.$user->get('id', 0);
			$db->setQuery($query);
			$db->query();

			//own accounts
			$query = 'DELETE * FROM #__ownservice_accounts WHERE user_id='.$user->get('id', 0);
			$db->setQuery($query);
			$db->query();

			//own files
			$query = 'DELETE * FROM #__ownservice_files WHERE userid='.$user->get('id', 0);
			$db->setQuery($query);
			$db->query();

			//own transactions
			$query = 'DELETE * FROM #__ownservice_transactions WHERE user_id='.$user->get('id', 0);
			$db->setQuery($query);
			$db->query();
		}

		// Set data to save
		$post['id']					= $id;
		$post['user_id']			= $user->get('id', 0);
		$post['group_id']			= isset($post['group_id'])?$post['group_id']:1;
		$post['lastname']			= strtoupper($post['lastname']); 
		/*
		 * lets save the Ownservice user object
		*/
		if(!$model->store($post)){
			$mainframe->enqueueMessage(JText::_('OWNSERVICE_ERROR_SAVE_USER'), 'message');
			$mainframe->enqueueMessage($user->getError(), 'error');
			return $this->execute('edit');
		}

		// Manage Files

		$path		= OwnserviceHelper::getParams('path', 'images/stories/ownservices'); 
		$dir		= JPATH_SITE.DS.$path.DS.$model->get('user_id').DS;

		if($isNew){
			if($dh = opendir($dir)){
				while(($file = readdir($dh))!== false){
					if(file_exists($dir.$file)){ 
						@unlink($dir.$file);
					}
				}
					closedir($dh);
			}

			//$query = 'DELETE FROM #__ownservice_files WHERE userid='.$model->get('user_id');
			//$db->setQuery($query);
			//$db->query();
		}

		$file 		= JRequest::getVar( 'Filedata', '', 'files', 'array' );

		// Set FTP credentials, if given
		jimport('joomla.client.helper');
		JClientHelper::setCredentialsFromRequest('ftp');

		// Make the filename safe
		jimport('joomla.filesystem.file');

		for($i=0,$n=count($file['name']); $i<$n; $i++) {
			if(empty($file['name'][$i])) {
				break;
			}
			
			$file['name'][$i]	= JFile::makeSafe($file['name'][$i]);

			//get the extension to record it in the DB
			$ext		= strtolower(JFile::getExt($file['name'][$i]));

			if (isset($file['name'])) {

				$filepath = JPath::clean(JPATH_SITE.DS.$path.DS.$model->get('user_id').DS.strtolower($file['name'][$i]));

				if (!OwnserviceHelper::canUpload( $file, $i, $err )) {
					if ($format == 'json') {
						jimport('joomla.error.log');
						$log = &JLog::getInstance('upload.error.php');
						$log->addEntry(array('comment' => 'Invalid: '.$filepath.': '.$err));
						header('HTTP/1.0 415 Unsupported Media Type');
						jexit('Error. Unsupported Media Type!');
					} else {
						JError::raiseNotice(100, strtolower($file['name'][$i]).' '.JText::_($err));
						break;
					}
				}

				if (JFile::exists($filepath)) {
					if ($format == 'json') {
						jimport('joomla.error.log');
						$log = &JLog::getInstance('upload.error.php');
						$log->addEntry(array('comment' => 'File already exists: '.$filepath));
						header('HTTP/1.0 409 Conflict');
						jexit('Error. File already exists');
					} else {
						JError::raiseNotice(100, strtolower($file['name'][$i]).' '.JText::_('Error. File already exists'));
						break;
					}
				}

				if (!JFile::upload($file['tmp_name'][$i], $filepath)) {
					if ($format == 'json') {
						jimport('joomla.error.log');
						$log = &JLog::getInstance('upload.error.php');
						$log->addEntry(array('comment' => 'Cannot upload: '.$filepath));
						header('HTTP/1.0 400 Bad Request');
						jexit('Error. Unable to upload file');
					} else {
						JError::raiseWarning(100, strtolower($file['name'][$i]).' '.JText::_('Error. Unable to upload file'));
						break;
					}
				} else {
					if ($format == 'json') {
						jimport('joomla.error.log');
						$log = &JLog::getInstance();
						$log->addEntry(array('comment' => $folder));
						jexit('Upload complete');
					} else {
						$mainframe->enqueueMessage(strtolower($file['name'][$i]).' '.JText::_('Upload complete'));
					}
				}

				// insert only the new records
				$createdate = & JFactory::getDate();
				$query = 'INSERT INTO #__ownservice_files (`userid`, `filename`, `ext`, `uploaded`, `uploaded_by`) '
					.' VALUES('.$model->get('user_id').','.$db->Quote(strtolower($file['name'][$i])).','.$db->Quote($ext).','.$db->Quote($createdate).','.$me->get('id').')';
				
				$db->setQuery($query);
				$db->query();
			}

		}

		$delete = JRequest::getVar( 'delete', array(0), 'post', 'array' );

		if(count( $delete ) > 0) {
			foreach($delete as $del) {
				if( $del > 0 ) {
					$query = 'SELECT * FROM #__ownservice_files WHERE id='.$del;
					$db->setQuery($query);
					$data = $db->loadObject();

					$query = 'DELETE FROM #__ownservice_files where id='.$del;
					$db->setQuery($query);
					if(!$db->query()) {
						JError::raiseNotice(100, JText::_('Unable to delete:').$data->filename);
						break;
					}

					$path	  = OwnserviceHelper::getParams('path', 'images/stories/ownservices'); 
					$origpath = JPath::clean(JPATH_SITE.DS.$path.DS.$data->userid.DS.$data->filename);
					// delete the original image from file manager
					if (!JFile::delete($origpath)) {
						JError::raiseNotice(100, JText::_('Unable to delete:').$data->filename);
					}

					$mainframe->enqueueMessage(JText::_('succesfully removed:').$data->filename);
				}
			}
		}

		if($id > 0){
			$msg = JText::sprintf( 'SUCCESSFULLY SAVED CHANGES TO USER', $user->get('name') );
		} else {
			$msg = JText::sprintf( 'SUCCESSFULLY SAVED USER', $user->get('name') );
		}

		$link = JRoute::_('index.php?option=com_ownservice&view=user&id='.$model->get('id'));

		$this->setRedirect($link, $msg);
	}

	/**
	 * Removes the record(s) from the database
	 */
	function delete()
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$me = & JFactory::getUser();
		$app = & JFactory::getApplication();

		if($me->gid < 25){
			$canDelete = Ownservice::checkAccess('user', 'delete', 'user', 'all');
			if (!$canDelete) {
				//JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		$db 		=& JFactory::getDBO();
		$acl		=& JFactory::getACL();
		$id 		=JRequest::getVar( 'id', 0, 'post', 'int' );

		if ($id <= 0) {
			JError::raiseError(500, JText::_('OWNSERVICE_SELECT_USER_TO_DELETE', true ) );
		}

		$model	= $this->getModel('Users');
		$row	= $model->getUser($id);

		$user =& JUser::getInstance((int)$row->user_id);

		//delete user
		//$user->delete();

		$user->block = 1;
		$user->save();

		/*
		 * delete the ownservices user 
		*/
		$model->delete($id);

		$msg = JText::_( 'USER DELETED' );

		$link = JRoute::_('index.php?option=com_ownservice&view=users');

		$this->setRedirect( $link, $msg);
	}

	/**
	 * logic for cancel an action
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function cancel()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$app = & JFactory::getApplication();

		$link = JRoute::_('index.php?option=com_ownservice&view=users');

		$this->setRedirect( $link );
	}

	/**
	 * Download logic
	 *
	 * @access public
	 * @since 1.0
	 */
	function download()
	{
		global $mainframe;
		
		jimport('joomla.filesystem.file');

		$id 		= JRequest::getInt( 'id', 0 );
		$db			= &JFactory::getDBO();
		$user		= & JFactory::getUser();

		if($user->gid < 25){
			$canDownload = Ownservice::checkAccess('user', 'download', 'user', 'all');
			if (!$canDownload) {
				//JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
				JError::raiseWarning(500, JText::_('ALERTNOTAUTH') );
				$mainframe->redirect(JRoute::_('index.php?option=com_ownservice'));
			}
		}

		$query  = 'SELECT * FROM #__ownservice_files WHERE id='.$id;

		$db->setQuery($query);
		$data = $db->loadObject();

		$basePath = JPATH_SITE.DS.OwnserviceHelper::getParams('path', 'images/stories/ownservices');

		$abspath = str_replace(DS, '/', JPath::clean($basePath.DS.$data->userid.DS.$data->filename));

		if (!JFile::exists($abspath)) {
			$msg 	= JText::_( 'OWNSERVICE_REQUESTED_FILE_DOES_NOT_EXIST_ANYMORE' );
			$link 	= 'index.php';
			$this->setRedirect($link, $msg);
			return;
		}
		
		//get filesize and extension
		$size 	= filesize($abspath);
		$ext 	= $data->ext;
	
		// required for IE, otherwise Content-disposition is ignored
		if(ini_get('zlib.output_compression')) {
			ini_set('zlib.output_compression', 'Off');
		}

		switch( $ext )
		{
			case "pdf":
				$ctype = "application/pdf";
				break;
			case "exe":
				$ctype="application/octet-stream";
				break;
			case "rar":
			case "zip":
				$ctype = "application/zip";
				break;
			case "txt":
				$ctype = "text/plain";
				break;
			case "doc":
				$ctype = "application/msword";
				break;
			case "xls":
				$ctype = "application/vnd.ms-excel";
				break;
			case "ppt":
				$ctype = "application/vnd.ms-powerpoint";
				break;
			case "gif":
				$ctype = "image/gif";
				break;
			case "png":
				$ctype = "image/png";
				break;
			case "jpeg":
			case "jpg":
				$ctype = "image/jpg";
				break;
			case "mp3":
				$ctype = "audio/mpeg";
				break;
			default:
				$ctype = "application/force-download";
		}
		
		/*		
		JResponse::setHeader('Pragma', 'public');
		JResponse::setHeader('Expires', 0);
		JResponse::setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
		JResponse::setHeader('Cache-Control', 'private', false);
		JResponse::setHeader('Content-Type', $ctype);
		JResponse::setHeader('Content-Disposition', 'attachment; filename="'.$data.'";');
		JResponse::setHeader('Content-Transfer-Encoding', 'binary');
		JResponse::setHeader('Content-Length', $size);
		*/
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false); // required for certain browsers
		header("Content-Type: $ctype");
		//quotes to allow spaces in filenames
		header("Content-Disposition: attachment; filename=\"".$data->filename."\";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".$size);

		readfile($abspath);
		$mainframe->close();
	}
}